//
// Created by vista on 2017/12/8.
//

#ifndef P_P2_H
#define P_P2_H


#ifndef NULL
#define NULL 0
#endif

//Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;

    explicit ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        ListNode *result = NULL;

        int p = 0;

        ListNode * ptr = result;

        while (l1 || l2){
            ListNode * tmp;
            if(l1 && l2) {
                tmp = new ListNode((l1->val + l2->val + p) % 10);
                p = (l1->val + l2->val + p) / 10;
            }
            else if(l1)
            {
                tmp = new ListNode((l1->val + p) % 10);
                p = (l1->val + p) / 10;
            }else {
                tmp = new ListNode(( l2->val + p) % 10);
                p = ( l2->val + p) / 10;
            }
            if(ptr == NULL){
                ptr = result = tmp;
            }else{
                ptr->next = tmp;
            }
            ptr = tmp;
            if(l1)
                l1 = l1->next;
            if(l2)
                l2 = l2->next;
        }
        if(p){
            ptr->next = new ListNode(p);
        }

        return result;
    }
};

#endif //P_P2_H
